<template>
    <Dialog v-model="dialogVisible" title="编辑">
        <el-form
            ref="formRef"
            v-loading="formLoading"
            :model="formData"
            :rules="formRules"
            label-width="80px"
        >
            <el-form-item label="参数名称" prop="name">
                <el-input v-model="formData.name" placeholder="请输入参数名称" disabled/>
            </el-form-item>
            <el-form-item v-if="formData.configKey == 'yxt.order.rules'" label="参数键值" prop="value">
                <Editor v-model="formData.value" height="300px"/>
            </el-form-item>
            <el-form-item v-else label="参数键值" prop="value">
                <el-input v-model="formData.value" placeholder="请输入参数键值" type="textarea" :rows="3"/>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input v-model="formData.remark" placeholder="请输入内容" type="textarea" :rows="5" maxlength="500" show-word-limit/>
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="dialogVisible = false">取 消</el-button>
        </template>
    </Dialog>
</template>
<script lang="ts" setup>
import {useConfigApi} from "@/api/yxt/config";
import {useMessage} from "@/components/Notice";

defineOptions({name: "InfraConfigForm"});

const configApi = useConfigApi();

const dialogVisible = ref(false); // 弹窗的是否展示
const formLoading = ref(false); // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = ref({
    id: undefined,
    name: "",
    configKey: "",
    value: "",
    remark: ""
});
const formRules = reactive({
    value: [{required: true, message: "参数键值不能为空", trigger: "blur"}],
});
const formRef = ref();

const open = async (id: number) => {
    dialogVisible.value = true;
    resetForm();
    if (id) {
        formLoading.value = true;
        try {
            formData.value = await configApi.getObj(id);
        } finally {
            formLoading.value = false;
        }
    }
};
defineExpose({open});

const emit = defineEmits(["success"]);
const submitForm = async () => {
    formRef.value?.validate(async (valid: any) => {
        if (valid) {
            formLoading.value = true
            try {
                await configApi.updateObj(formData.value);
                useMessage("修改成功");
                dialogVisible.value = false;
                emit('success');
            } finally {
                formLoading.value = false;
            }
        }
    });
};

const resetForm = () => {
    formData.value = {
        id: undefined,
        name: "",
        configKey: "",
        value: "",
        remark: ""
    };
    formRef.value?.resetFields();
};
</script>
